package raceReservationServer.raceServerGateway;

import java.util.LinkedList;
import java.util.List;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.CannotProceed;
import org.omg.CosNaming.NamingContextPackage.NotFound;

import corbaServer.corba.*;
import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;

public class CorbaRaceServerGateway implements IRaceServerGateway {
	private ICorbaServer objServidor;
	public CorbaRaceServerGateway(String serviceUri){
		
		try {
			String[] params= serviceUri.split(" ");
			String[] orb_args = {"-ORBInitialHost", params[0],"-ORBInitialPort", params[1]};
			ORB orb = ORB.init(orb_args,null);
			org.omg.CORBA.Object objRef= orb.resolve_initial_references("NameService");
			NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);
			String name = params[2];
			objServidor = ICorbaServerHelper.narrow(ncRef.resolve_str(name));
		} catch (InvalidName e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotFound e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CannotProceed e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (org.omg.CosNaming.NamingContextPackage.InvalidName e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public List<RaceDO> getRaces() {
		LinkedList<RaceDO> result = new LinkedList<RaceDO>();
		RaceDTO[] aux;
		aux= objServidor.getRaces();
		String name;
		float dist;
		String date;
		int places;
		for(int i=0; i<aux.length; i++){
			
			name= aux[i].name;
			dist= aux[i].distance;
			date= aux[i].date;
			places= aux[i].places;
			RaceDO rdo= new RaceDO(name, dist, date, places);
			result.add(rdo);
		}
		return result;
	}
}
